package com.openspring.platform.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.openspring.framework.dao.AbstractSpringGenericDAO;
import com.openspring.platform.dao.RoleDAO;
import com.openspring.platform.model.Role;

@Repository("roleDAO")
public class RoleDAOImpl extends AbstractSpringGenericDAO<Role, Long> implements RoleDAO {

	@Override
	public int deleteUserRole(Long id) {
        return getJdbcTemplate().update("DELETE FROM emp.t_platform_user_role WHERE \"roleId\" = ?", id);
	}

	@Override
	public int[] insertUserRole(Long id, Long...userId) {
		if(userId == null || userId.length == 0) {
			return new int[]{0};
		}
		List<Object[]> batch = new ArrayList<Object[]>();
        for (Long _userId : userId) {
            Object[] values = new Object[] {_userId, id};
            batch.add(values);
        }
        return getJdbcTemplate().batchUpdate("INSERT INTO emp.t_platform_user_role(\"userId\", \"roleId\") VALUES (?, ?)", batch);
	}

	@Override
	public List<Map<String, Object>> queryUserRole(Long roleId, Long deptId) {
		String sql = "SELECT t1.id, t1.\"userName\", CASE WHEN ((SELECT t2.\"userId\" FROM emp.t_platform_user_role t2 WHERE t2.\"userId\" = t1.id AND t2.\"roleId\" = ?) IS NULL) THEN false ELSE true END AS checked FROM emp.t_platform_user t1 WHERE t1.\"deptId\" = ?";
		return getJdbcTemplate().queryForList(sql, roleId, deptId);
	}

	@Override
	public List<Map<String, Object>> queryUserRole(Long roleId) {
		String sql = "SELECT t1.*, CASE WHEN ((SELECT t2.\"userId\" FROM emp.t_platform_user_role t2 WHERE t2.\"userId\" = t1.id AND t2.\"roleId\" = ?) IS NULL) THEN false ELSE true END AS checked FROM emp.t_platform_user t1";
		return getJdbcTemplate().queryForList(sql, roleId);
	}
}
